package com.coder.algorithm.sort;

/**
 * 快速排序
 *
 * @author yuhushuan
 * @date 2020/6/7 00:54
 */
public class QuickSort implements Sort {
    public QuickSort() {
        System.out.println("快速排序");
    }

    @Override
    public void sort(int[] array) {
        QuickSort(array, 0, array.length - 1);
    }

    private void QuickSort(int[] array, int start, int end) {
        if (array == null) return;
        if (start < 0 || end >= array.length || start > end) return;

        int index = partition(array, start, end);
        if (index > start)
            QuickSort(array, start, index - 1);
        if (index < end)
            QuickSort(array, index + 1, end);
    }

    /**
     * 快速排序算法——partition
     *
     * @param array
     * @param start
     * @param end
     * @return
     */

    private int partition(int[] array, int start, int end) {
        if (array == null || start < 0 || end < start){
            throw new IllegalArgumentException("Invalid Argument");
        }
        int index = (int) (start + Math.random() * (end - start + 1));
        swap(array, index, end);// 基准位于末尾

        int small = start - 1;
        for (int i = start; i <= end; i++)
            if (array[i] <= array[end]) {
                small++;
                if (i > small) {
                    swap(array, i, small);
                }
            }
        return small;
    }

    /**
     * 交换数组内两个元素
     *
     * @param array
     * @param i
     * @param j
     */

    private static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}
